# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################


import time
import datetime
import utils.pgsql.base.pgconn as pgconn

"""
tech pay management
add 
delete
modify
...
"""
_tblName = "tbl_techpay"

_DB_SCRIPT = f"""
CREATE TABLE IF NOT EXISTS {_tblName} (
                "payId" SERIAL PRIMARY KEY ,        
                "outTradeNo"  VARCHAR(64) NOT NULL default '' unique,    
                "transactionId" VARCHAR(256) NOT NULL default '' unique,  
                "openId" VARCHAR(256) NOT NULL default '',  
                "productId" VARCHAR(256) NOT NULL default '',  
                "videoUrl" VARCHAR(256) NOT NULL default '',  
                "duration" VARCHAR(256) NOT NULL default '',  
                "thumbImageUrl" VARCHAR(256) NOT NULL default '',         
                "channelId"  INTEGER NOT NULL default 0,  
                "caseId"  INTEGER NOT NULL default 0, 
                "createTime"  VARCHAR(64) NOT NULL default '',  
                "endTime"  VARCHAR(64) NOT NULL default '',     
                "totalFee" INTEGER NOT NULL default 0,  
                "cashFee" INTEGER NOT NULL default 0,   
                "updateTime" VARCHAR(32) NOT NULL default '',
                "buyType"  VARCHAR(64) NOT NULL default '' 
                );
"""


class Pgtechpay:
    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

 

    # def create_dayTbl(self):
    #     """
    #     
    #     :return:
    #     """
    #     partitionTbl = "{}_{}".format(_tblName, commfunc.utcnow_ymd())
    #     sql = """CREATE TABLE IF not exists {} PARTITION OF {} FOR VALUES FROM (\'{}\') TO (\'{}\');""".format(
    #         partitionTbl, _tblName,
    #         commfunc.utcday(),
    #         commfunc.utcndayafter(1),
    #         )
    #     return self._pgConn.exec(sql)

    def addpay(self, dic) -> str:
        if "createTime" not in dic:
            dic["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if "updateTime" not in dic:
            dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

  
        sql = "insert into {} ({}) values ({}) ".format(_tblName, sql_key, sql_val[:-1])
        return self._pgConn.exec(sql)

    def modify(self, outTradeNo, cashfee, dic) -> bool:
        dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])   + f""" "outTradeNo" = '{outTradeNo}' and "totalFee" = '{cashfee}' """
        return self._pgConn.exec(sql)

    def allCase(self, caseId) -> list:
        sql = f"""select * from {_tblName} where "caseId" = {caseId} order by "createTime" desc LIMIT 200"""
        return self._pgConn.exec_fetchall(sql)

    def PageCase(self, caseId, pageNo, pageSize) -> list:
        sql = f"""select * from {_tblName} where "caseId" = {caseId} order by "createTime" LIMIT {pageSize} OFFSET {(pageNo-1) * pageSize}"""
        return self._pgConn.exec_fetchall(sql)

    def PageAll(self, pageNo, pageSize) -> list:
        sql = f"""select * from {_tblName} order by "createTime" LIMIT {pageSize} OFFSET {(pageNo-1) * pageSize}"""
        return self._pgConn.exec_fetchall(sql)

    def GetAllYesterDay(self, date) -> list:
        sql = f"""select * from {_tblName} where Date("createTime") = '{date}' order by "createTime" """
        return self._pgConn.exec_fetchall(sql)

     
    def paybytime(self, time, endtime) -> dict:
        sql = "select * from  tbl_techpay  where  \"createTime\" between '{}' and '{}' ".format(
            time, endtime
        )
        return self._pgConn.exec_fetchall(sql)

     
    def payoperatortime(self, ids, time, endtime) -> dict:
        sql = 'select Count(a."payId") As Count from {}   a left join tbl_case n on a."caseId"=n."caseId"   where  n."operatorId" = {} and a."createTime" between \'{}\' and \'{}\' '.format(
            _tblName, ids, time, endtime
        )
        # print(sql)
        return self._pgConn.exec_fetchone(sql)

     
    def operatorsum(self, ids) -> dict:
        sql = 'select Count(a."payId") As Count , SUM(a."totalFee") AS nums from {}   a left join tbl_case n on a."caseId"=n."caseId"   where  n."operatorId" = {} '.format(
            _tblName, ids
        )
        # print(sql)
        return self._pgConn.exec_fetchone(sql)

    # def temonecompose(self, ids) -> dict:
    #     sql = 'Select a."activityName",m."templateName",m."templateId",Count(a."activityName") As Count FROM {} a left join tbl_activity n on a."activityName"=n."activityName"  left join tbl_template m on m."templateId"=n."templateId" where  a."caseId" = \'{}\' and m."caseId" = \'{}\'  group  by a."activityName",m."templateName",m."templateId" order by Count desc '.format(
    #         _tblName, ids, ids
    #     )
    #     return self._pgConn.exec_fetchall(sql)

    #  
    # def all(self) -> list:
    #     sql = f"""select * from {_tblName} order by "recordId" desc LIMIT 1000"""
    #     return self._pgConn.exec_fetchall(sql)

    #  
    # def updateShareNumPlus1(self, projectId) -> bool:
    #     sql = "update {} set \"ShareNum\"=\"ShareNum\"+1 where \"ProjectId\"=\'{}\'".format(
    #         _tblName, projectId)
    #     res = self._pgConn.exec(sql)
    #     return res

    #  
    # def updateBuyNumPlus1(self, projectId) -> bool:
    #     sql = "update {} set \"BuyNum\"=\"BuyNum\"+1 where \"ProjectId\"=\'{}\'".format(
    #         _tblName, projectId)
    #     res = self._pgConn.exec(sql)
    #     return res

    #  
    # def updateDownloadNumPlus1(self, projectId) -> bool:
    #     sql = "update {} set \"DownloadNum\"=\"DownloadNum\"+1 where \"ProjectId\"=\'{}\'".format(
    #         _tblName, projectId)
    #     res = self._pgConn.exec(sql)
    #     return res


    def PagetechCase(
        self, caseId, pageNo, pageSize, startTime, endTime, order_status, limit=""
    ) -> list:
        tmp = f' and "templateName" SIMILAR TO \'%({limit})%\' ' if limit else ""
        sql = f"""select count(0) over () totalNum , * from {_tblName} 
                where "caseId" = {caseId} 
                and "createTime" >= '{startTime}'   
                and "createTime" <= '{endTime}' {tmp}
                order by "createTime" desc LIMIT {pageSize} OFFSET {(pageNo-1) * pageSize}"""
        if order_status: # 退款
            sql = f"""select count(0) over () totalNum , * from {_tblName} 
                            where "caseId" = {caseId} 
                            and "createTime" >= '{startTime}'   
                            and "createTime" <= '{endTime}'
                            and "order_status" = '{order_status}'  {tmp}
                            order by "createTime" desc LIMIT {pageSize} OFFSET {(pageNo - 1) * pageSize}"""
        return self._pgConn.exec_fetchall(sql)


    def PagetechAll(self, pageNo, pageSize, startTime, endTime, order_status="", limit="") -> list:
        tmp = f' and "order_status" = \'{order_status}\'' if order_status else ''
        sql = f"""select count(0) over () totalNum , * from {_tblName} 
                where "createTime" >= '{startTime}'   
                and "createTime" <= '{endTime}' {tmp}
                order by "createTime" desc LIMIT {pageSize} OFFSET {(pageNo-1) * pageSize}"""
        return self._pgConn.exec_fetchall(sql)


    def chantechpay(self, channelId,pageNo, pageSize, startTime, endTime) -> list:
        sql = f"""select count(0) over () totalNum , * from {_tblName} 
                where "channelId" = {channelId} 
                and "createTime" >= '{startTime}'   
                and "createTime" <= '{endTime}'
                order by "createTime" desc LIMIT {pageSize} OFFSET {(pageNo-1) * pageSize}"""
        return self._pgConn.exec_fetchall(sql)

    def casebytime(self, ids, starttime, endtime) -> dict:
        sql = "select * from {} where \"caseId\" = '{}' and  \"createTime\" between '{}' and '{}' ".format(
            _tblName, ids, starttime, endtime
        )
        return self._pgConn.exec_fetchall(sql)

    def allbytime(self,  starttime, endtime) -> dict:
        sql = "select * from {} where    \"createTime\" between '{}' and '{}' ".format(
            _tblName,  starttime, endtime
        )
        return self._pgConn.exec_fetchall(sql)

    def single_byid(self,transactionId):
        sql = f"select * from tbl_techpay where \"transactionId\" ='{transactionId}'"
        return self._pgConn.exec_fetchone(sql)

    def update_order_status(self,transactionId,refund=None,total=None):
        # ALTER table tbl_techpay ADD order_status VARCHAR(20) DEFAULT 'success';
        # 根据流水号退款
        extral = f", note='实际退款：{refund/100} 元' " if refund != total else ''
        sql = f"update tbl_techpay set order_status='refund' {extral} where \"transactionId\" ='{transactionId}'"
        return self._pgConn.exec(sql)

    def update_cloud_url(self,transactionId,cloud_url=None):
        sql = f'update tbl_techpay set cloud_url=\'{cloud_url}\' where "transactionId"=\'{transactionId}\''
        return self._pgConn.exec(sql)
    